<template>
  <el-dialog
    width="50%"
    :visible="visible"
    title="管理分组模块"
    @update:visible="$emit('update:visible', $event)"
    @close="closeHandle"
  >
    <div class="module-admin">
      <div class="head">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="insertEvent"
        >新增</el-button>
      </div>
      <el-table
        class="table-drag"
        :data="tableData"
        row-key="mod_id"
        height="360px"
      >
        <el-table-column>
          <template v-slot:header>
            <el-tooltip content="按住后可以上下拖动排序！">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </template>
          <template v-slot>
            <span class="drag-btn">
              <i class="el-icon-menu"></i>
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="模块名"
          align="center"
        >
          <template #default="{row}">
            <el-input
              ref="input"
              v-if="row.mod_name_edit"
              v-model="row.mod_name"
              @blur="blurHandle(row,'mod_name')"
            ></el-input>
            <p
              v-else
              @click="toInput(row,'mod_name')"
            >{{row.mod_name}}</p>
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          align="center"
        >
          <template #default="{row}">
            <el-input
              ref="input"
              v-if="row.note_edit"
              v-model="row.note"
              @blur="blurHandle(row,'note')"
            ></el-input>
            <p
              v-else
              class="text"
              @click="toInput(row,'note')"
            >{{row.note}}</p>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
        >
          <template #default="{row,$index}">
            <el-button
              type="text"
              @click="removeEvent(row,$index)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- <template #footer>
      <div class="btns">
        <el-button
          type="info"
          @click="cancel"
        >取消</el-button>
        <el-button
          type="primary"
          @click="save"
        >保存</el-button>
      </div>
    </template> -->
  </el-dialog>
</template>

<script type="text/javascript">
import Sortable from 'sortablejs'
import {
  addModule,
  updateModule,
  deleteModule
} from '@/api/system/project'
import { getModuleList } from '../../resource'
export default {
  name: 'ModuleAdmin',
  components: {},
  props: {
    type: {
      type: Number,
      default: 0 // 0标签 1处理结果
    },
    visible: {
      type: Boolean,
      required: true
    },
    projectId: [Number, String]
  },
  data () {
    return {
      tableData: [],
      showHelpTip: false,
      validRules: {
        mod_name: [{ required: true, message: '请输入模块名称' }]
      }
    }
  },
  methods: {
    init () {
      this.getModuleList()
    },
    insertEvent () {
      if (this.$refs.input) {
        this.inputFocus()
        return
      }
      this.tableData.push({
        client_id: Date.now(),
        pro_id: this.projectId,
        mod_name: '',
        mod_id: '',
        mod_idx: this.tableData.length
          ? this.tableData[this.tableData.length - 1].mod_id
          : -1,
        mod_pid: 0,
        mod_status: 1,
        note: '',
        mod_name_edit: true,
        note_edit: false
      })
      this.inputFocus()
    },
    getModuleList () {
      return getModuleList({
        pro_id: this.projectId
      }).then(list => {
        this.tableData = list.map(t => ({ ...t, mod_name_edit: false, note_edit: false }))
        this.$nextTick(() => {
          // 行的拖拽初始化
          this.rowDropInit()
        })
      })
    },
    async removeEvent (row, index) {
      if (row.mod_id) {
        this.$confirm('确定要删除此数据吗？', {
          title: '提示',
          type: 'warning'
        }).then(async () => {
          await deleteModule({ mod_id: row.mod_id })
          this.tableData.splice(index, 1)
          this.updated = true
          this.updateOrders()
        }).catch(() => { })
      } else {
        this.tableData.splice(index, 1)
      }
    },
    // 行拖拽
    rowDropInit () {
      if (this.dragObj) return
      this.dragObj = Sortable.create(document.querySelector('.table-drag tbody'), {
        handle: '.drag-btn',
        onEnd: ({
          newIndex,
          oldIndex
        }) => {
          const currRow = this.tableData.splice(oldIndex, 1)[0]
          this.tableData.splice(newIndex, 0, currRow)
          this.updated = true
          updateModule({
            mod_id: currRow.mod_id,
            mod_idx: newIndex === 0 ? 0 : this.tableData[newIndex - 1].mod_id
          }).then(() => {
            this.updateOrders()
          })
        }
      })
    },
    async blurHandle (row, key) {
      if (this.validate()) {
        if (row.mod_id) {
          await updateModule(row)
        } else {
          await addModule([row]).then(res => {
            row.mod_id = res.data[0].mod_id
            this.updateOrders()
          })
        }
        row[key + '_edit'] = false
        this.updated = true
      }
    },
    toInput (row, key) {
      if (this.validate()) {
        this.tableData.forEach(t => {
          for (const key in t) {
            if (key.endsWith('_edit')) t[key] = false
          }
        })
        row[key + '_edit'] = true
        this.inputFocus()
      }
    },
    validate () {
      const valid = this.tableData.every(t => t.mod_name.trim())
      if (!valid) {
        this.$message.warning('模块名不能为空！')
      }
      return valid
    },
    closeHandle () {
      this.$emit('close', !!this.updated)
    },
    cancel () {
      this.$emit('update:visible', false)
    },
    inputFocus () {
      this.$nextTick(() => {
        this.$refs.input && this.$refs.input.focus()
      })
    },
    dragdDispose () {
      if (this.dragObj) {
        this.dragObj.destroy()
        this.dragObj = null
      }
    },
    updateOrders () {
      this.tableData.forEach((item, index, arr) => {
        const prevItem = arr[index - 1]
        item.mod_idx = prevItem ? prevItem.mod_id : 0
      })
    }
  },
  watch: {
    visible (newVal) {
      newVal && this.$nextTick(this.init)
    }
  },
  beforeDestroy () {
    this.dragdDispose()
  }
}
</script>

<style lang="scss" scoped>
.module-admin {
  padding: 0 16px;
  margin-top: -20px;
  .head {
    text-align: right;
    margin-bottom: 20px;
  }
  .drag-btn {
    cursor: move;
  }
  .text {
    height: 36px;
    line-height: 36px;
    cursor: pointer;
  }
}
</style>
